﻿namespace ECommerce.Controls
{
	using System;
	using System.Linq;
	using System.Web.UI.WebControls;

	public partial class RecommendProducts16_23 : BaseUserControl
	{
		private Service.IProductService _ProductService;

		protected void Page_Load(object sender, EventArgs e)
		{
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			BindProducts();

			this.LRecommendProducts16_23Title.Text = GetLocalResourceString("RecommendProducts16_23.Title");
		}

		protected void RepeaterRecommedProducts16_23_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.DataItem != null)
			{
				System.Web.UI.WebControls.HyperLink hlImg = e.Item.FindControl("HyperLinkProdImg") as HyperLink;

				var theProduct = e.Item.DataItem as Data.Entity.Product;

				hlImg.NavigateUrl = "~/ProductDetail.aspx?productid=" + ((Data.Entity.Product)e.Item.DataItem).ProductID;
				hlImg.ImageUrl = "~/PictureHandler.ashx?picturesize=130&productid=" + ((Data.Entity.Product)e.Item.DataItem).ProductID;

				System.Web.UI.WebControls.HyperLink hlName = (System.Web.UI.WebControls.HyperLink)e.Item.FindControl("HyperLinkProdName");

				hlName.NavigateUrl = hlImg.NavigateUrl;
				string theName = ((Data.Entity.Product)e.Item.DataItem).Name;
				hlName.Text = theName.Length > 7 ? theName.Substring(0, 7) + "..." : theName;
				hlName.ToolTip = theName;
				hlImg.ToolTip = theName;
			}
		}

		private void BindProducts()
		{
			if (SiteContext.Current == null || SiteContext.Current.WorkingLanguage == null)
			{
				Server.Transfer("~/HomePage.aspx");
			}

			if (_ProductService == null)
			{
				_ProductService = new Service.ProductService();
			}

			var productByLang = _ProductService.GetProductsByLanguage(SiteContext.Current.WorkingLanguage.LanguageId);

			if (productByLang != null)
			{
				var products = (from p in productByLang
								where p.Recommend.GetValueOrDefault()
								orderby p.DisplayOrder
								select p).Skip(15).Take(8);

				RepeaterRecommedProducts16_23.DataSource = products;
				RepeaterRecommedProducts16_23.DataBind();
			}
			else
			{
				RepeaterRecommedProducts16_23.DataSource = null;
				RepeaterRecommedProducts16_23.DataBind();
			}
		}
	}
}